﻿@using System.Collections.Immutable
<FluentStack Style="margin: 20px;" Orientation="Orientation.Vertical">
    <FluentCheckbox Label="@($"All ({AreAllTypesVisible?.ToString() ?? "null"})")"
                    ThreeState="true"
                    ShowIndeterminate="false"
                    @bind-CheckState="AreAllTypesVisible" />
    @foreach (string resourceType in _allResourceTypes)
    {
        bool isChecked = _visibleResourceTypes.Contains(resourceType);
        <FluentCheckbox Label="@($"{resourceType} ({isChecked})")"
                        @bind-Value:get="isChecked"
                        @bind-Value:set="c => OnResourceTypeVisibilityChanged(resourceType, c)" />
    }
</FluentStack>


@code {

    private readonly ImmutableArray<string> _allResourceTypes = ["Project", "Executable", "Container"];
    private readonly HashSet<string> _visibleResourceTypes;

    public CheckboxThreeStateList()
    {
        _visibleResourceTypes = new HashSet<string>(_allResourceTypes);
    }

    protected void OnResourceTypeVisibilityChanged(string resourceType, bool isVisible)
    {
        if (isVisible)
        {
            _visibleResourceTypes.Add(resourceType);
        }
        else
        {
            _visibleResourceTypes.Remove(resourceType);
        }
    }

    private bool? AreAllTypesVisible
    {
        get
        {
            return _visibleResourceTypes.SetEquals(_allResourceTypes)
                ? true
                : _visibleResourceTypes.Count == 0
                    ? false
                    : null;
        }
        set
        {
            if (value is true)
            {
                _visibleResourceTypes.UnionWith(_allResourceTypes);
            }
            else if (value is false)
            {
                _visibleResourceTypes.Clear();
            }
        }
    }
}
